# coding:utf8

from appserver import db_store
import traceback
from models.entity.role_with_user import RoleWithUser
from models.entity.role_with_button import RoleWithButton

from sqlalchemy import or_

"""
角色表
"""


class Role(db_store.Model):
    __tablename__ = "roles"
    __bind_key__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'角色编号')
    name = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'角色名称')
    code = db_store.Column(db_store.String(32), nullable=False, unique=True, comment=u"角色编码")
    description = db_store.Column(db_store.String(255), comment=u"角色描述")
    status = db_store.Column(db_store.Integer, comment=u"状态")  # 0-正常 1-禁用

    def __repr__(self):
        return "<Role %s>" % self.name

    def save(self):
        if self.name is None:
            print("role save error: name cannot be none")
            return -1
        if self.code is None:
            print("role save error: code cannot be none")
            return -2
        try:
            db_store.session.add(self)
            db_store.session.commit()
            return 0
        except:
            print("----------------------------------table roles write error:\n----------------------------------\n%s\n----------------------------------" %(traceback.format_exc()))
            return -1

    def delete(self):
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return 0
        except:
            print("----------------------------------table users write error:\n----------------------------------\n%s\n----------------------------------" %(traceback.format_exc()))
            return -1

    @staticmethod
    def get_role_by_id(id_num):
        # 通过id获取角色实例
        return Role.query.filter_by(id=id_num).first()

    @staticmethod
    def get_role_by_name(name):
        # 通过name获取角色实例
        return Role.query.filter_by(name=name).first()

    @staticmethod
    def get_role_by_code(code):
        # 通过code获取角色实例
        return Role.query.filter_by(code=code).first()

    @staticmethod
    def get_roles_by_user(the_user):
        # 以python列表的形式返回某个用户的所有角色实例
        all_connector=RoleWithUser.query.filter_by(user_id=the_user.id).all()
        # print('all_connector',all_connector)
        rlist=[]
        for item in all_connector:
            # print('item-all_connector',item)
            the_role=Role.query.filter_by(id=item.role_id).first()
            # print('the_role', type(the_role), the_role)
            rlist.append(the_role)
        return rlist

    @staticmethod
    def get_role_all():
        # 以python列表的形式返回所有角色实例
        return Role.query.all()

    @staticmethod
    def get_role_dic(the_role):
        # 以python字典的形式返回角色实例的字典
        rdic={}
        rdic["id"]=the_role.id
        rdic["name"]=the_role.name
        rdic["code"]=the_role.code
        rdic["description"]=the_role.description
        rdic["status"]=the_role.status
        return rdic

    @staticmethod
    def add_role(name=None,code=None,description=None,status=None,buttons=None):
        new_role=Role()
        if name is None:
            print("name cannot be None")
            return -1
        else:
            new_role.name=name
        if code is None:
            print("code cannot be None")
            return -2
        else:
            new_role.code=code
        if buttons is None:
            print("buttons cannot be empty")
            return -6
        if not description is None:
            new_role.description=description
        if not status is None:
            new_role.status=status
        ret=new_role.save()
        if ret!=0:
            print("add_role error: role save error")
            return -3
        saved_list=[]
        for item in buttons:
            button_connector=RoleWithButton()
            button_connector.role_id=new_role.id
            button_connector.button_id=item.id
            ret=button_connector.save()
            if ret!=0:
                print("add_role error: role save error")
                for t_item in saved_list:
                    t_ret=t_item.delete()
                    if t_ret!=0:
                        print("add_role error: recovery error")
                        return -5
                return -4
            saved_list.append(button_connector)
        return 0
    
    @staticmethod
    def search(query_word):
        search_list=Role.query.filter(or_(Role.name.like("%"+query_word+"%"),Role.code.like("%"+query_word+"%"),
                                                            Role.description.like("%"+query_word+"%"))).all()
        tlist=[]
        for item in search_list:
            tlist.append(Role.get_role_dic(item))
        rdic={
                        "success":1,
                        "error_code":None,
                        "error_msg":None,
                        "data":tlist
                }
        return rdic

    @staticmethod
    def get_roles_by_user_id(user_id):
        return [Role.query.filter_by(id=r.role_id).first() for r in RoleWithUser.query.filter_by(user_id=user_id).all()]
